package pers.ht.mbpo.util;

import java.sql.*;
import java.util.Locale;
import java.util.ResourceBundle;

public class DBUtil {

    private static String URL;//数据库链接地址
    private static String USERNAME;//用户名
    private static String PASSWORD;//密码
    private static String DRIVER;//MySQL驱动

    //读取资源属性文件（properties）
    private static ResourceBundle rb = ResourceBundle.getBundle("pers.ht.mbpo.util.DB-config", Locale.US);


    //禁止外部实例化
    private DBUtil() {
    }

    static {
        URL = rb.getString("jdbc.url");
        USERNAME = rb.getString("jdbc.username");
        PASSWORD = rb.getString("jdbc.password");
        DRIVER = rb.getString("jdbc.driver");
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //定义一个获取数据库链接的方法
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("获取数据库连接失败");
        }
        return conn;
    }

    //关闭数据库链接
    public static void close(ResultSet rs, Statement stat, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (stat != null) stat.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
